import axios from "axios";
import store from "@/store";
import router from "@/router";
import { message } from "ant-design-vue";

axios.defaults.baseURL = "/api";

/* 请求拦截器 */
axios.interceptors.request.use(
  (config) => {
    // 添加token到header
    const token = store.getters.user.token;
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/* 响应拦截器 */
axios.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (
      data.code == 1002 ||
      data.code == 1003 ||
      data.code == 1004 ||
      data.code == 2202 ||
      data.code == 2003
    ) {
      if (router.currentRoute.value.path == "/Login") return;
      message.error({
        content: "登录信息已失效，请重新登录！",
        key: 1,
      });
      // 跳转首页
      router.push("/Login");
      return;
    }
    if (data.code && data.code != 200) {
      message.error(data.msg);
      return Promise.reject();
    }

    return Promise.resolve(response.data);
  },
  (error) => {
    // 处理响应错误
    if (error?.response?.data?.msg) message.error(error?.response?.data?.msg);
    return Promise.reject(error.response);
  }
);

const get = (url: string, params: any) => {
  if (!params) params = {};
  return axios.get(url, { params });
};
const post = (url: string, params: any) => {
  if (!params) params = {};
  return axios.post(url, params);
};
const del = (url: string, params: any) => {
  if (!params) params = {};
  return axios.delete(url, { params });
};
const upload = (url: string, params: any) => {
  if (!params) params = {};
  const file = new FormData();
  for (const key in params) {
    file.append(key, params[key]);
  }
  return axios.post(url, file);
};

const getAndLoadData = async (url: string, params: any) => {
  const result: any = await get(url, params);
  return result?.data;
};
const postAndLoadData = async (url: string, params: any) => {
  const result: any = await post(url, params);
  return result?.data;
};
const delAndLoadData = async (url: string, params: any) => {
  const result: any = await del(url, params);
  return result?.data;
};

export default {
  get,
  getAndLoadData,
  post,
  postAndLoadData,
  del,
  delAndLoadData,
  upload,
};
